package com.example.yangjintingtest.controller;

import com.example.yangjintingtest.domain.Admin;
import com.example.yangjintingtest.domain.BlogArticle;
import com.example.yangjintingtest.domain.BlogComment;
import com.example.yangjintingtest.domain.StaticticsBo;
import com.example.yangjintingtest.mapper.AdminMapper;
import com.example.yangjintingtest.service.SiteService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminMapper adminMapper;

    @GetMapping("/login")//显示登录页面
    public String tologinPage() {
        return "back/login";
    }

//    @GetMapping("")//后台首页
//    public String index() {
//        return "back/index1";
//    }

    @PostMapping("/toLogin")//提交登录，登录成功跳转到后台首页
    public String login(Admin admin, HttpSession httpSession, Model model) {
        Admin admin1 = adminMapper.userLogin(admin);
        if (admin1 != null) {
            httpSession.setAttribute("admin", admin1);  // 将用户对象添加到Session
            model.addAttribute("admin", admin1);
            return "redirect:/admin";    // 跳转到后台首页
//            return "back/header";
        }
        else {
            model.addAttribute("msg", "账号或密码错误，请重新输入！");
            return "back/login";
        }
    }

    @Autowired
    SiteService siteService;
    @GetMapping("")//后台首页
    public String index(HttpServletRequest request){
        // 获取最新的5篇博客、评论以及统计数据
        List<BlogArticle> articles = siteService.recentArticles(5);
        List<BlogComment> comments = siteService.recentComments(5);
        StaticticsBo staticticsBo = siteService.getStatistics();
        // 向Request域中存储数据
        request.setAttribute("comments", comments);
        request.setAttribute("articles", articles);
        request.setAttribute("statistics", staticticsBo);
        return "back/index";
//        return "back/header";

    }

    /**
     * 跳转到测试案例页面
     * @param model
     * @return
     */
    @GetMapping(value = "/ue")
    public String ue(Model model) { return "index"; }
}
